package com.yonyou.base.flower.web;

import com.yonyou.base.common.utils.DiscernUtils;
import com.yonyou.base.common.utils.JsonHelper;
import com.yonyou.base.common.web.MessageResult;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/**
 * 识别模块
 */
@Controller
@RequestMapping("/flower/discern")
public class FlowerDiscernController {

    private String[] fileType = {"data:image/bmp;base64,", "data:image/png;base64,", "data:image/jpeg;base64,"};

    /**
     * 图片识别，仅支持jpg/png/bmp格式
     *
     * @return
     */
    @RequestMapping("/upload.do")
    @ResponseBody
    public Object upload(@RequestBody Map param) {
        String base64Str = MapUtils.getString(param, "base64Str");
        //去掉头信息
        String apiStr = getApiStr(base64Str);
        if (apiStr == null) {
            return new MessageResult(MessageResult.STATUS_ERROR, "图片格式错误,仅支持jpg/png/bmp格式");
        }
        //调用API识别图片
        String str = DiscernUtils.getDiscernResult(apiStr);
        Map<String, Object> map = JsonHelper.readMapValue(str);
        if (map == null) {
            return new MessageResult(MessageResult.STATUS_ERROR, "识别失败");
        }
        Map result = (Map) ((List) MapUtils.getObject(map, "result")).get(0);
        Map baikeInfo = MapUtils.getMap(result, "baike_info");
        for (Object key : baikeInfo.keySet()) {
            result.put(key, baikeInfo.get(key));
        }
        result.put("baike_info", null);
        return new MessageResult(MessageResult.STATUS_SUCCESS, "操作成功", result);
    }

    private String getApiStr(String base64Str) {
        for (String type : fileType) {
            if (base64Str.startsWith(type)) {
                return base64Str.substring(type.length());
            }
        }
        return null;
    }

}
